import store from '../store'
import { setLocalStorage, getLocalStorage } from '@/utils/localStorage'
export default {
  install(Vue, options = {}) {
    Vue.directive('permission', { // 判断按钮是否有权限
      inserted: (el, binding) => {
        let btnPermissions = store.getters.tags
        // console.log('btnPermissions', btnPermissions)
        if (binding.value && typeof binding.value === 'string' && btnPermissions.indexOf(binding.value) === -1) {
          el.parentNode.removeChild(el)
        } else if (binding.value && typeof binding.value === 'object') {
          let flag = true // 为true的时候删除节点，因为没权限
          binding.value.forEach(v => {
            if (btnPermissions.indexOf(v) > -1) {
              flag = false
            }
          })
          if (flag) {
            el.parentNode.removeChild(el)
          }
        }
      }
    })
    // 判断按钮是否有权限, 有权限代码的时候，是无权限的，这个是和permission相反的
    // permission是有权限代码就有权限
    // unpermission是有权限代码就无权限
    Vue.directive('unpermission', {
      inserted: (el, binding) => {
        let btnPermissions = store.getters.tags
        // console.log('btnPermissions', btnPermissions)
        if (binding.value && typeof binding.value === 'string' && btnPermissions.indexOf(binding.value) > -1) {
          el.parentNode.removeChild(el)
        } else if (binding.value && typeof binding.value === 'object') {
          let flagIsDel = false // 为true的时候删除节点，因为没权限
          binding.value.forEach(v => {
            if (btnPermissions.indexOf(v) > -1) {
              flagIsDel = true
            }
          })
          if (flagIsDel) {
            el.parentNode.removeChild(el)
          }
        }
      }
    })
    Vue.directive('selectCreate', { // el-select创建条目-change后回填值
      bind: function (el, binding, vnode) {
        let multipleFlag = vnode.componentInstance.multiple
        if (el.tagName.toLowerCase() !== 'input') {
          el = el.getElementsByTagName('input')[0]
        }
        el.addEventListener('change', function () {
          let vm = vnode.context
          let attr = vnode.data.model.expression
          let obj = null
          if (attr.indexOf('.') > -1) {
            let attrs = attr.split('.')
            attrs.forEach((v, i) => {
              if (i === 0) {
                obj = vm[v]
              } else if (i === (attrs.length - 1)) {
                if (multipleFlag) {
                  if (obj[v].indexOf(el.value) === -1) {
                    obj[v].push(el.value)
                  }
                } else {
                  obj[v] = el.value
                }
              } else {
                obj = obj[v]
              }
            })
          } else {
            if (multipleFlag) {
              if (vm[attr].indexOf(el.value) === -1) {
                vm[attr].push(el.value)
              }
            } else {
              vm[attr] = el.value
            }
          }
        })
      }
    })
    Vue.directive('dialogDrag', {
      bind(el, binding, vnode, oldVnode) {
        // 获取拖拽内容头部
        const dialogHeaderEl = el.querySelector('.el-dialog__header')
        // 如果使用element的组件应写成.el-dialog
        const dragDom = el.querySelector('.el-dialog')
        dialogHeaderEl.style.cursor = 'move'

        // 初始化的时候设定初始值
        let elWidth = dragDom.style.width.replace('px', '')
        if (dragDom.style.width.indexOf('%') > -1) {
          let xiaoshu = dragDom.style.width.replace('%', '') / 100
          elWidth = document.body.clientWidth * xiaoshu
        }
        let left = (document.body.clientWidth - elWidth) / 2
        let value = ''
        try {
          value = vnode.data.attrs['drag-top']
        }catch (e) {
          
        }
        dragDom.style.left = `${left}px`
        dragDom.style.top = value || `50px`

        // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
        const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null)

        // 鼠标按下事件
        dialogHeaderEl.onmousedown = (e) => {
          // 鼠标按下，计算当前元素距离可视区的距离 (鼠标点击位置距离可视窗口的距离)
          const disX = e.clientX - dialogHeaderEl.offsetLeft
          const disY = e.clientY - dialogHeaderEl.offsetTop

          // 获取到的值带px 正则匹配替换
          let styL, styT

          // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
          if (sty.left.includes('%')) {
            styL = +document.body.clientWidth * (+sty.left.replace(/\%/g, '') / 100)
            styT = +document.body.clientHeight * (+sty.top.replace(/\%/g, '') / 100)
          } else {
            styL = +sty.left.replace(/\px/g, '')
            styT = +sty.top.replace(/\px/g, '')
          }

          // 鼠标拖拽事件
          document.onmousemove = function (e) {
            // 通过事件委托，计算移动的距离 （开始拖拽至结束拖拽的距离）
            const l = e.clientX - disX
            const t = e.clientY - disY

            let finallyL = l + styL
            let finallyT = t + styT

            // 边界值判定 注意clientWidth scrollWidth区别 要减去之前的top left值
            // dragDom.offsetParent表示弹窗阴影部分
            /*  if (finallyL < 0) {
                          finallyL = 0
                        } else if (finallyL > dragDom.offsetParent.clientWidth - dragDom.clientWidth - dragDom.offsetParent.offsetLeft) {
                          finallyL = dragDom.offsetParent.clientWidth - dragDom.clientWidth - dragDom.offsetParent.offsetLeft
                        }

                        if (finallyT < 0) {
                          finallyT = 0
                        } else if (finallyT > dragDom.offsetParent.clientHeight - dragDom.clientHeight - dragDom.offsetParent.offsetLeft) {
                          (
                            finallyT = dragDom.offsetParent.clientHeight - dragDom.clientHeight - dragDom.offsetParent.offsetLeft
                          )
                        } */

            // 移动当前元素
            dragDom.style.left = `${finallyL}px`
            dragDom.style.top = `${finallyT}px`

            // 将此时的位置传出去
            // binding.value({x:e.pageX,y:e.pageY})
          }

          document.onmouseup = function (e) {
            document.onmousemove = null
            document.onmouseup = null
          }
        }
      }
    })
    Vue.directive('setDefault',
      (el, binding, vnode) => {
        // 该指令作用是让清空的数据置为默认值
        let vm = vnode.context
        let attr = vnode.data.model.expression
        let value = vnode.data.model.value
        let defaultValue = null // 不传值默认为null
        if (binding.value) {
          defaultValue = binding.value
        }
        let obj = null
        if (value === '') {
          if (attr.indexOf('.') > -1) {
            let attrs = attr.split('.')
            attrs.forEach((v, i) => {
              if (i === 0) {
                obj = vm[v]
              } else if (i === (attrs.length - 1)) {
                obj[v] = defaultValue
              } else {
                obj = obj[v]
              }
            })
          } else {
            vm[attr] = defaultValue
          }
        }
      }
    )
    Vue.directive('horizontalDrag', {
      bind: function (el, binding, vnode) {
        const dragbar = el.querySelector('.dragbar')
        let vm = vnode.context
        dragbar.onmousedown = e => {
          const _parentNode = el.parentNode
          const _pMask = _parentNode.querySelector('.main_mask')
          _pMask ? _pMask.style.display = 'block' : ''
          _parentNode.style.cursor = 'ew-resize'
          const cx = e.pageX - el.clientWidth
          document.onmousemove = function (e) {
            e.preventDefault()
            const l = e.clientX - cx
            let hisActivedIndex = getLocalStorage('hisActivedIndex')
            if (hisActivedIndex == 2) {
              if (l > 480) {
                vm.sidebarOption.width = `${l}px`
              }
            } else {
              if (l > 400) {
                vm.sidebarOption.width = `${l}px`
              }
            }
          }
          document.onmouseup = function (e) {
            document.onmousemove = null
            document.onmouseup = null
            _parentNode.style.cursor = 'default'
            _pMask ? _pMask.style.display = 'none' : ''
          }
        }
      },
      update(el, binding) {
        // console.log('update', binding.value)
        // if (!binding.value.contentShow) {
        //   el.style.marginLeft = -el.offsetWidth + 'px'
        // } else {
        //   el.style.marginLeft = '0px'
        // }
      }
    })
    Vue.directive('herticalDrag', {
      bind: function (el, binding, vnode) {
        const dragbar = el.querySelector('.draggerVbar')
        const draggerTable = el.querySelector('.el-table__body-wrapper')
        let vm = vnode.context
        draggerTable.style.height = vm.hisTableHeight - 48 + 'px'
        dragbar.onmousedown = e => {
          const _parentNode = el.parentNode
          const _elTableRefs = _parentNode.querySelector('.main_mask')
          const _pMask = _parentNode.querySelector('.main_mask')
          _pMask ? _pMask.style.display = 'block' : ''
          _parentNode.style.cursor = 'sn-resize'
          const cx = e.pageY - el.clientHeight

          document.onmousemove = function (e) {
            e.preventDefault()
            const l = e.clientY - cx
            let maxHeight = window.g.applyHis && window.g.applyHis.isHideApplyInfoBoxAndUseDialog ? window.innerHeight - document.querySelector('.apply_form').offsetHeight - 110 :348
            if (l > 48 && l < maxHeight) {
              vm.hisTableHeight = l
              draggerTable.style.height = vm.hisTableHeight - 48 + 'px'
              setLocalStorage('yjyy-hisTableHeight', l)
            }
          }
          document.onmouseup = function (e) {
            document.onmousemove = null
            document.onmouseup = null
            _parentNode.style.cursor = 'default'
            _pMask ? _pMask.style.display = 'none' : ''
          }
        }
      },
      update(el, binding) {
        // console.log('update', binding.value)
        // if (!binding.value.contentShow) {
        //   el.style.marginLeft = -el.offsetWidth + 'px'
        // } else {
        //   el.style.marginLeft = '0px'
        // }
      }
    })
  }
}
